<?php

namespace app\backend\controller\im;

use app\common\controller\Basic;
use app\common\service\hrm\CompanyService;
use app\common\service\im\ChatlogService;
use app\common\service\im\GroupService;
use app\common\service\im\GroupUserService;
use app\common\service\hrm\DeptService;
use app\common\service\pmm\ConfigService;
use app\common\service\pmm\FlowAuditService;
use app\common\service\pmm\FlowBillService;
use app\common\service\pmm\FlowBrowsingService;
use app\common\service\pmm\MessageService;
use app\common\service\sys\UserService;
use PhpOffice\PhpSpreadsheet\Cell\Cell;

/**
 * IM聊天控制器
 * @author kaige
 * @update ©2022-05-12
 */
class Chat extends Basic
{

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        // 当前控制器服务实例化
        $this->service = new GroupService(); //群
    }
    /**
     * 群-列表
     * @return array|string
     */
    public function grouplist()
    {
        if ($this->request->isGet()) {
            $data = input('param.');
            return json($this->service->_list($data));
        }
        return _jerr(1000);
    }

    /**
     * 群-添加
     * @return array|string
     */
    public function groupadd()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            return json($this->service->saveData($data));
        }
        if ($this->request->isGet()) {
            return _jok('ok', [
                'companyList' => CompanyService::getCompanyList(),
            ]);
        }
        return _jerr(1000);
    }

    /**
     * 群-编辑
     * @return array|string
     */
    public function groupedit()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            return json($this->service->saveData($data));
        }
        if ($this->request->isGet()) {
            $id = input('id/d', 0);
            $data = $this->service->getInfoById($id);
            $data['companyList'] = CompanyService::getCompanyList();
            if (isset($data['chat_head'])) {
                $data['chat_head_url'] = _img($data['chat_head']);
            }
            return _jok('ok', $data);
        }
        return _jerr(1000);
    }

    /**
     * 群-删除
     */
    public function groupdel()
    {
        if ($this->request->isPost()) {
            $id = input('id/d', 0);
            if ($id === 0) {
                return _jerr(1002);
            }
            if ($this->service->delete($id)) {
                return _jok(1025);
            };
            return _jerr(1026);
        }
        return _jerr(1000);
    }

    /*******群用户******/
    /**
     * 后台-IM群用户列表
     * @return array|string
     */
    public function groupuserlist()
    {
        if ($this->request->isGet()) {
            $gus = new GroupUserService();
            $data = input('param.');
            if (!isset($data['group_id']) || empty($data['group_id'])) {
                return json(_layui(0, []));
            }
            return json($gus->_list($data));
        }
        return _jerr(1000);
    }

    /**
     * 添加
     * @return array|string
     */
    public function groupuseradd()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            return json((new GroupUserService())->saveData($data));
        }
        if ($this->request->isGet()) {
            return _jok('ok', [
                'companyList' => CompanyService::getCompanyList(),
            ]);
        }
        return _jerr(1000);
    }

    /**
     * 编辑
     * @return array|string
     */
    public function groupuseredit()
    {
        $gus = new GroupUserService();
        if ($this->request->isPost()) {
            $data = input('param.');
            return json($gus->saveData($data));
        }
        if ($this->request->isGet()) {
            $id = input('id/d', 0);
            $data = $gus->getInfoById($id);
            $data['companyList'] = CompanyService::getCompanyList();
            if (isset($data['chat_bg'])) {
                $data['chat_bg_url'] = _img($data['chat_bg']);
            }
            return _jok('ok', $data);
        }
        return _jerr(1000);
    }

    /**
     * 删除
     */
    public function groupuserdel()
    {
        if ($this->request->isPost()) {
            $id = input('id/s', '');
            if ($id === 0) {
                return _jerr(1002);
            }
            if ((new GroupUserService())->_del($id)) {
                return _jok(1025);
            };
            return _jerr(1026);
        }
        return _jerr(1000);
    }

    /*****************聊天记录管理*********************/
    /**
     * 聊天记录
     */
    public function chatloglist()
    {
        if ($this->request->isGet()) {
            $data = input('param.');
            return json((new ChatlogService())->_list($data));
        }
        return _jerr(1000);
    }

    /**
     * 聊天记录删除
     */
    public function chatlogdel()
    {
        if ($this->request->isPost()) {
            $id = input('id/s', '');
            if ($id === 0) {
                return _jerr(1002);
            }
            if ((new ChatlogService())->_del($id)) {
                return _jok(1025);
            };
            return _jerr(1026);
        }
        return _jerr(1000);
    }
    /*****************PC szim*********************/
    public function sziminit()
    {
        if ($this->request->isGet()) {
            $result = ['code' => 0, 'status' => 1, 'msg' => 'ok', 'data' => [
                'mine' => [
                    'id' => $this->user['id'],
                    'username' => $this->user['real_name'],
                    'avatar' => _img($this->user['avatar']),
                    'sign' => $this->user['sign'],
                    'status' => $this->user['online'] === 1 ? 1 : 0
                ],
                'friend' => (new DeptService())->getDeptUseSzim(),
                'group' => (new GroupUserService())->getUserQunList($this->user['id']),
                'chatobj' => (new ChatlogService())->getUserChatList($this->user['id'])
            ]];
            return json($result);
        }
        return _jerr(1000);
    }
    public function szimqun()
    {
        if ($this->request->isGet()) {
            $id = $this->request->param('id/d', 0);
            $result = ['code' => 0, 'status' => 1, 'msg' => 'ok', 'data' => [
                'list' => (new GroupUserService())->getImGroupUserListSzim($id)
            ]];
            return json($result);
        }
        return _jerr(1000);
    }
    //用户加入的所有群
    public function getUserQunList()
    {
        if ($this->request->isGet()) {
            $result = (new GroupUserService())->getUserQunList($this->user['id']);
            return _jok('', $result);
        }
        return _jerr(1000);
    }

    /**
     * 获取与对象聊天记录 默认20条
     */
    public function getUserChatObjList()
    {
        if ($this->request->isGet()) {
            $input = [
                'uid' => $this->user['id'],
                'rid' => input('rid/d', 0),
                'page' => input('page/d', 1),
                'limit' => input('limit/d', 20),
                'read' => input('read', 0)
            ];
            $cls = new ChatlogService();
            $data = $cls->getUserChatObjList($input);
            return json($data);
        }
        return _jerr(1000);
    }

     /**
     * 获取群聊天记录 默认20条
     */
    public function getUserGroupChatList()
    {
        if ($this->request->isGet()) {
            $input = [
                'uid' => $this->user['id'],
                'group_id' => input('group_id/d', 0),
                'page' => input('page/d', 1),
                'limit' => input('limit/d', 20),
                'read' => input('read', 0)
            ];
            $cls = new ChatlogService();
            $data = $cls->getUserGroupChatList($input);
            return _jok('',$data);
        }
        return _jerr(1000);
    }

    /***********************流程相关*****************/
    /**
     * 消息盒子
     */
    public function msgbox()
    {
        if ($this->request->isGet()) {
            $pms = new MessageService();
            $post = $this->request->param();
            $post['user_id'] = $this->user['id'];
            if (isset($post['limit']) && empty($post['limit'])) {
                $post['limit'] = 20;
            }
            if (empty($post['limit'])) {
                $post['limit'] = 20;
            }
            $post['msgbox'] = 1;
            $list = $pms->_list($post);
            if ($list) {
                $outlist = $this->msg_format($list['data']);
                $data = [
                    "code" => $list['code'],
                    "pages" => ceil($list['count'] / $post['limit']),
                    "data" => $outlist
                ];
            }
            return json($data);
        }
        return _jerr(1000);
    }

    /**
     * 根据前端json格式化数据
     */
    protected function msg_format($list)
    {
        $data = [];
        if ($list) {
            foreach ($list as $k => $v) {
                $data[] = [
                    "id" => $v['id'],
                    "content"       => $v['glmodu']['name'] . '-' . $v['glbill']['put_name'] . '- 摘要[' . $v['glbill']['flow_brief'] . ']',
                    "rece_id"       => $v['rece_id'],
                    "chat_type"     => $v['chat_type'],
                    "type"          => $v['type'],
                    "rece_id_name"  => $v['rece_id_name'],
                    "status"        => $v['status'],
                    "time"          => $v['create_time'],
                    "url"           => $v['m_url'],
                    "flow_number"   => $v['flow_number'],
                    "msg_type"      => '流程审批',
                    "step_id_status" => $v['step_id_status']
                ];
            }
        }
        return $data;
    }

    /**
     * 消息已读
     */
    public function hasread()
    {
        if ($this->request->isPost()) {
            $pms = new MessageService();
            $post = $this->request->post();
            $result = $pms->hasread($post, $this->user);
            return json($result);
        }
        return _jerr(1000);
    }

    /**
     * 消息删除
     */
    public function delmessage()
    {
        if ($this->request->isPost()) {
            $pms = new MessageService();
            $id = $this->request->param('id');
            $result = $pms->delmessage($id, $this->user['id']);
            return json($result);
        }
        return _jerr(1000);
    }
}
